// ActionScript file
package Avocado.util {

	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class AvocadoXmlLoader extends EventDispatcher {

		public var result:XML;
		
		public var url:String;

		private var request:URLRequest;
		private var loader:URLLoader;
		
		/**
		 * @param urlString	caminho do xml a ser lido
		 * ***/
		public function AvocadoXmlLoader(urlString:String, target:IEventDispatcher=null) {
			super(target);

			this.url = urlString;

			this.request = new URLRequest(this.url);
			this.loader = new URLLoader(request);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatus);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loaderError);
			loader.addEventListener(ProgressEvent.PROGRESS, loaderProgress);
			loader.addEventListener(Event.COMPLETE, xmlComplete);
			loader.load(request);
		}
		
		/**
		 * 
		 * ***/
		public function load(_urlString:String):AvocadoXmlLoader{
			return new AvocadoXmlLoader(_urlString);
		} 

		/**
		 * 
		 * ***/
		private function loaderProgress(e:ProgressEvent):void{
			this.dispatchEvent(e);
		}

		/**
		 * 
		 * ***/
		private function loaderError(e:IOErrorEvent):void{
			this.dispatchEvent(e);
		}

		/**
		 * 
		 * ***/
		private function httpStatus(e:HTTPStatusEvent):void{
			this.dispatchEvent(e);
		}

		/**
		 * 
		 * ***/
		private function xmlComplete(e:Event=null):void {
			loader.removeEventListener(ProgressEvent.PROGRESS, loaderProgress);
			loader.removeEventListener(Event.COMPLETE, xmlComplete);
			if (e.target != null){
				var xmlString:String = new String(e.target.data);
				result = new XML(xmlString);
			} else {
				new Error('Xml não carregado corretamente', e); 
			}
			this.dispatchEvent(new Event(Event.COMPLETE));
		}

	}

}
